package com.tonann.app.conf;

import com.tonann.app.mapper.BaseMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Data
@Service
public class AsyncServiceImpl<T> implements AsyncService<T> {

    @Async("asyncServiceExecutor")
    public void executeAsync(List<T> list, BaseMapper<T> baseMapper, CountDownLatch countDownLatch) {
        try {
//            log.warn("start executeAsync");
            //异步线程要做的事情
            baseMapper.insertBatch(list);
//            log.warn("end executeAsync");
        } finally {
            countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
        }
    }

    @Override
    public int startMultiThread(List<T> list, BaseMapper<T> baseMapper) {
        //测试每100条数据插入开一个线程
        List<List<T>> lists = ConvertHandler.splitList(list, 100);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<T> listSub : lists) {
            this.executeAsync(listSub, baseMapper, countDownLatch);
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            log.error("阻塞异常:" + e.getMessage());
        }
        return lists.size();
    }

    @Override
    public List<T> getPage(int page, int pageSize, BaseMapper<T> baseMapper) {
        return getRecordList(page, pageSize, baseMapper);
    }


    public List<T> getRecordList(int page, int pageSize, BaseMapper<T> baseMapper) {
        List<T> list = new ArrayList<>();
        int listSize = pageSize;
        int pageCurrent = page;
        while (listSize == pageSize) {
            List<T> subList = baseMapper.selectPage(page, pageSize);
            listSize = subList.size();
            list.addAll(subList);
            pageCurrent++;
            page = pageCurrent * pageSize;
        }
        return list;
    }
}
